<?php
namespace Admin\Controller;

use Common\Controller\AdminbaseController;

class ExamsController extends AdminbaseController{
	
	protected $exams_model;
	protected $exam_terms_model;
	protected $ques_terms_model;
	protected $exams_users_model;
	protected $exam_card_model;
	protected $targets=array("_blank"=>"新标签页打开","_self"=>"本窗口打开");
	//protected $question_types=array("1"=>"单选题","2"=>"多项选择题","3"=>"填空题","4"=>"判断题","5"=>"主观题");
	
	public function _initialize() {
		parent::_initialize();
		$this->exams_model = D("Admin/Exams");
		$this->exam_terms_model = D("Portal/ExamTerms");
		$this->ques_terms_model = D("Portal/QuesTerms");
		$this->exams_users_model = D("Portal/ExamsUsers");
		$this->exam_card_model = M("ExamCard");
		//$this->assign("question_types",$this->$question_types);
	}
	
	// 后台考试列表
	public function index($id=0,$exam_term_id=0,$ques_term_id=0,$keyword=''){
	    
    	$map=null;
    	if($id>0) $map['a.id']=$id;
    	if($exam_term_id>0) $map['a.exam_term']=$exam_term_id;
    	if($ques_term_id>0) $map['a.ques_term']=$ques_term_id;
    	//if($type_id>0) $map['a.exam_type']=$type_id;
    	if(!empty($keyword)) $map['a.exam_name']=$keyword;
    	if(isset($map))$map['_logic']='OR';

    	$map['exam_status']=array('lt',3);
    	$this->_lists($map);
    	$this->assign('keyword',$keyword);
    	$this->_getExamTree();
    	$this->_getQuesTree();
    	$this->display();
	}
	// 后台考试列表
	public function recycle($id=0,$exam_term_id=0,$ques_term_id=0,$keyword=''){	     
	    $map=null;
	    if($id>0) $map['a.id']=$id;
	    if($exam_term_id>0) $map['a.exam_term']=$exam_term_id;
	    if($ques_term_id>0) $map['a.ques_term']=$ques_term_id;
	    //if($type_id>0) $map['a.exam_type']=$type_id;
	    if(!empty($keyword)) $map['a.exam_name']=$keyword;
	    if(isset($map))$map['_logic']='OR';
    	$map['_complex'] = array('a.exam_status'=>3);
	    $this->_lists($map);
	    $this->assign('keyword',$keyword);
	    $this->_getExamTree();
	    $this->_getQuesTree();
	    $this->display('exams/recycle');
	}
	// 报名和考试情况
	public function users($exam_id=0,$dept='',$keyword=''){
	    $map=null;
	    if(!empty($dept)) $map['c.dept']=$dept;
	    if(!empty($keyword)) $map['c.user_nicename']=$keyword;
    	if(isset($map)){
    	    $map['_logic']='OR';
    	    $where['_complex'] = $map;
    	}
    	
    	$where['a.exam_id']  = $exam_id;
    	
        $users_list=$this->exams_users_model
        ->alias("a")
        ->join("__USERS__ c ON a.user_id = c.id")
        ->where($where)
        ->select();
        //echo $this->exams_users_model->getLastSql();
        $this->assign('exam_id',$exam_id);
        $this->assign('keyword',$keyword);
        $this->assign('users_list',$users_list);
	    $this->display();
	}
	// 考试添加
	public function add(){
	    $paper_list=M('paper')->where('paper_type=1')->select();
	    $this->assign("paper_list",$paper_list);
    	$this->_getExamTree();
    	$this->_getQuesTree();
		$this->display();
	}
	
	
	// 考试添加提交
	public function add_exams(){
		if(IS_POST){

		    $count=$this->exams_model->where("exam_name='%s'",$_POST['exam_name'])->count();
		    if($count){
		        $this->error("考试名称已存在，请修改后重试！");
		    }
		    
		    $data['exam_name']=I('exam_name');
		    $data['exam_term']=I("exam_term",0,'intval');
		    $data['exam_type']=I("exam_type",0,'intval');//新增考试方式字段
		    $data['signin_type']=I("signin_type",0,'intval');//新增报名参加考试方式字段
		    //(!($data['signin_type']==2&&!empty($data['signin_user_list'])))||$this->error("请指定参加考试的用户！");
		    
		    $data['ques_term']=I("ques_term",0,'intval');
		    $data['exam_status']=I("exam_status",0,'intval');
		    
		    $start_time_array=I("exam_start_time");
		    $date=strtotime($start_time_array['day']);
		    $start_time=mktime($start_time_array['hour'],$start_time_array['min'],0,date('m',$date),date('d',$date),date('Y',$date));
		    
		    $signin_start_time=I("signin_start_time");//新增报名开始和结束时间
		    $signin_end_time=I("signin_end_time").' 23:59:59';;//新增报名开始和结束时间
		    !empty($signin_start_time)||$this->error("报名开始和结束时间不能为空！");
		    !empty($signin_end_time)||$this->error("报名开始和结束时间不能为空！");
		    strtotime($signin_start_time)>=strtotime($signin_end_time)&&$this->error("报名开始时间必须早于结束时间！");
		    
		    $data['signin_start_time']=$signin_start_time;//新增报名开始和结束时间
		    $data['signin_end_time']=$signin_end_time;//新增报名开始和结束时间
		    
		    $data['exam_start_time']=date('Y-m-d H:i:s',$start_time);
		    strtotime($data['exam_start_time'])>strtotime($signin_end_time)||$this->error("考试开始时间必须晚于报名结束时间！");
		    
		    
		    $data['exam_duration']=I("exam_duration",0,'intval');
		    $data['exam_duration']>0||$this->error("考试时长应大于0分钟！");
		    
		    $data['paper_id']=I("paper_id",0,'intval');
		    
		    $data['listorder']=I("listorder",0,'intval');
            $data['user_id']=get_current_admin_id();
		    
			if ($this->exams_model->create($data)!==false) {
				if ($this->exams_model->add()!==false) {
					$this->success("添加成功！", U("exams/index"));
				} else {
					$this->error("添加失败！");
				}
			} else {
				$this->error($this->exams_model->getError());
			}		
		}
	}
	
	// 考试编辑
	public function edit(){
		$id=  I("get.id",0,'intval');
		$exams=$this->exams_model->where("id=$id")->find();
		$exam_terms = $this->exam_terms_model->order(array("listorder"=>"asc"))->select();
		$ques_terms = $this->ques_terms_model->order(array("listorder"=>"asc"))->select();
		$exam_term_id = $exams['exam_term'];
		$ques_term_id = $exams['ques_term'];
		
		$paper_list=M('paper')->where('paper_type=1')->select();
		$this->assign("paper_list",$paper_list);
		
		$this->_getExamTermTree(array($exam_term_id));
		$this->_getQuesTermTree(array($ques_term_id));
		$this->assign('exams',$exams);
		$this->assign("exam_terms",$exam_terms);
		$this->assign("ques_terms",$ques_terms);
		$this->assign("targets",$this->targets);
		$this->display();
		
	}
	
	// 考试编辑
	public function edit_exams(){
		if (IS_POST) {
            $count=$this->exams_model->where("id<>%d and exam_name='%s'",I("id"),$_POST['exam_name'])->count();
            if($count){
                $this->error("试卷名称已存在，请修改后重试！");
            }
            $id=  I("id",0,'intval');
		    $data['id']=$id;
		    $data['exam_name']=I('exam_name');
		    $data['exam_term']=I("exam_term",0,'intval');
		    $data['ques_term']=I("ques_term",0,'intval');
		    $data['exam_status']=I("exam_status",0,'intval');
		    
		    $data['exam_type']=I("exam_type",0,'intval');
		    $data['signin_type']=I("signin_type",0,'intval');
		    $data['exam_result_show']=I("exam_result_show",0,'intval');
		    
		    $signin_start_time=I("signin_start_time");//新增报名开始和结束时间
		    $signin_end_time=I("signin_end_time").' 23:59:59';//新增报名开始和结束时间
		    !empty($signin_start_time)||$this->error("报名开始和结束时间不能为空！");
		    !empty($signin_end_time)||$this->error("报名开始和结束时间不能为空！");
		    strtotime($signin_start_time)>=strtotime($signin_end_time)&&$this->error("报名开始时间必须早于结束时间！");

		    $data['signin_start_time']=$signin_start_time;//新增报名开始和结束时间
		    $data['signin_end_time']=$signin_end_time;//新增报名开始和结束时间
		    
		    $start_time_array=I("exam_start_time");
		    $date=strtotime($start_time_array['day']);
		    $start_time=mktime($start_time_array['hour'],$start_time_array['min'],0,date('m',$date),date('d',$date),date('Y',$date));
		    
		    $data['exam_start_time']=date('Y-m-d H:i:s',$start_time);
		    $data['exam_duration']=I("exam_duration",0,'intval');
		    $data['paper_id']=I("paper_id",0,'intval');
		    
		    $data['listorder']=I("listorder",0,'intval');
		    $data['user_id']=get_current_admin_id();
		    
			if ($this->exams_model->save($data)!==false) {
                $this->success("编辑成功！");
			} else {
                $this->success("编辑成功！");
			}
		}
	}
	/**
	 * 准考证管理
	 */
	public function card($exam_id=0,$key=null){
	    $exam_list=$this->exams_model->where('exam_type=1')->select();
	    $this->assign("exam_list",$exam_list);
	    
	    $exam_id==0||$where['exam_id']=$exam_id;
	    empty($key)||$where['id_card']=array('like','%'.$key.'%');
	    
        $question_terms=array();
        $ques_terms_data=$this->ques_terms_model->select();
        foreach ($ques_terms_data as $term){
            $question_terms[$term['term_id']]=$term['name'];
        }
        $this->assign("ques_terms",$question_terms);
        
        $exam_terms=array();
        $exam_terms_data=$this->exam_terms_model->select();
        foreach ($exam_terms_data as $term){
            $exam_terms[$term['term_id']]=$term['name'];
        }
        $this->assign("exam_terms",$exam_terms);
	    
	    $count=$this->exam_card_model
	    ->field('c.id')
	    ->alias('c')
	    ->join('left join __EXAMS__ e on c.exam_id=e.id')
	    ->order('c.id desc')
	    ->where($where)
	    ->count();
	     
	    $page = $this->page($count, 20);    
	    
	    $card_list=$this->exam_card_model
	    ->field('c.*,e.exam_name,e.exam_term,e.ques_term,e.exam_start_time')
	    ->alias('c')
	    ->join('left join __EXAMS__ e on c.exam_id=e.id')
	    ->where($where)
	    ->order('c.id desc')
	    ->limit($page->firstRow , $page->listRows)
	    ->select();
	    $this->assign("page", $page->show('Admin'));
	    $this->assign("exam_id",$exam_id);
	    $this->assign("key",$key);
	    $this->assign("card_list",$card_list);
	    //echo $this->exam_card_model->getLastSql();
	    $this->_getExamTree();
	    $this->_getQuesTree();
	    $this->display();
	}
	/**
	 * 准考证添加
	 */
	public function card_add(){
	    $exam_list=$this->exams_model->where('exam_type=1')->select();
	    $this->assign("exam_list",$exam_list);
	    $this->_getExamTree();
	    $this->_getQuesTree();
	    $this->display();
	}
	/** 
	 * 准考证生成 
	 */
	public function card_add_post(){
	    if (IS_POST) {
	        $id_card_list=trim(I('idcard_list'));
	        //dump($id_card_list);
	        empty($id_card_list)&&$this->error("请填写身份证列表信息！");
	        
	        $exam_id=I('exam_id');
	        empty($exam_id)&&$this->error("请选择一个考试！");	        
	        
	        $id_card_arr=explode(" ",str_replace(array("\r\n", "\r", "\n"), " ", $id_card_list));//explode('\r\n',$id_card_list);
	        //var_dump($id_card_arr);
	        //$data['idcard_list']=I('idcard_list');
	        $exam_card_data=array();
	        foreach($id_card_arr as $idcard){
	            if(!empty($idcard)){
    	            $exam_card_item['id_card']=$idcard;
    	            $exam_card_item['exam_id']=$exam_id;
    	            $exam_card_item['code']=strtoupper(str_pad($exam_id,5,'0',STR_PAD_LEFT).uniqid());
    	            $exam_card_data[]=$exam_card_item;
	            }
	        }
	        $ret=$this->exam_card_model->addAll($exam_card_data);
	        if ($ret!==false) {
	            $this->success("生成成功！共生成".$ret."条。");
	        } else {
	            $this->success("生成失败！");
	        }
	    }
	}
	/**
	 * 导出到EXCEL
	 */
	public function card_list_export($exam_id=0,$key=null){
	    $exam_id==0||$where['exam_id']=$exam_id;
	    empty($key)||$where['id_card']=array('like','%'.$key.'%');
	    $where['card_status']=0;
	    $data=$this->exam_card_model	    
	    ->field("id,id_card,code")
	    ->where($where)->order('id asc')->select();
	    
	    create_xls($data,'考试准考证'.date('Y-m-d H:i:s',time()));
	}
	/**
	 * 删除准考证
	 */
	public function card_delete(){
	    if(isset($_GET['id'])){
	        $id = I("get.id",0,'intval');
	        if ($this->exam_card_model->where(array('id'=>$id))->save(array('card_status'=>1)) !==false) {
	            $this->success("删除成功！");
	        } else {
	            $this->error("删除失败！");
	        }
	    }
	
	    if(isset($_POST['ids'])){
	        $ids = I('post.ids/a');
	         
	        if ($this->exam_card_model->where(array('id'=>array('in',$ids)))->save(array('card_status'=>1))!==false) {
	            $this->success("删除成功！");
	        } else {
	            $this->error("删除失败！");
	        }
	    }
	}
	/**
	 * 考试报名
	 */
	public function signin_list($exam_id=0){
	    
	    $exam_list=$this->exams_model->where('exam_type=1')->select();
	    $this->assign("exam_list",$exam_list);
	     
	    $exam_id==0||$where['exam_id']=$exam_id;
	     
	    $question_terms=array();
	    $ques_terms_data=$this->ques_terms_model->select();
	    foreach ($ques_terms_data as $term){
	        $question_terms[$term['term_id']]=$term['name'];
	    }
	    $this->assign("ques_terms",$question_terms);
	    
	    $exam_terms=array();
	    $exam_terms_data=$this->exam_terms_model->select();
	    foreach ($exam_terms_data as $term){
	        $exam_terms[$term['term_id']]=$term['name'];
	    }
	    $this->assign("exam_terms",$exam_terms);
	    
	    $where=array();
	    $request=I('request.');
	
	    if(!empty($request['uid'])){
	        $where['id']=intval($request['uid']);
	    }
	    $where['user_type']=2;
	    if(!empty($request['keyword'])){
	        $keyword=$request['keyword'];
	        $keyword_complex=array();
	        $keyword_complex['user_login']  = array('like', "%$keyword%");
	        $keyword_complex['user_nicename']  = array('like',"%$keyword%");
	        $keyword_complex['user_email']  = array('like',"%$keyword%");
	        $keyword_complex['_logic'] = 'or';
	        $where['_complex'] = $keyword_complex;
	    }
	
	    $users_model=M("Users");
	     
	    $count=$users_model->where($where)->count();
	    $page = $this->page($count, 20);
	     
	    $list = $users_model
	    ->where($where)
	    ->order("create_time DESC")
	    ->limit($page->firstRow . ',' . $page->listRows)
	    ->select();
	     
	    $this->assign('list', $list);
	    $this->assign("page", $page->show('Admin'));
	     
	    $this->display();
	}
	/**
	 * 选择报名
	 */
	public function signin_post(){
	    $exam_id=I('exam_id');
	    empty($exam_id)&&$this->error("请选择要报名的考试！");
        $exam_data=$this->exams_model->find($exam_id);
        empty($exam_data)&&$this->error("无效的考试！");     
        $exam_data['exam_status']>0&&$this->error("考试已被删除！");

        $id = I("id",0,'intval');
	    if(!empty($id)){
	        
	        $data=array(
	          'user_id'=>$id,
	          'exam_id'=>$exam_id,
	          'paper_id'=>$exam_data['paper_id'],
	          'status'=>0
	        );
	        
	        if ($this->exams_users_model->where($data)->count()>0) {
	            $this->success("（重复）报名成功！");
	        } else if($this->exams_users_model->add($data)) {
	            $this->success("报名成功！");
	        } else {
	            $this->error("报名失败！");
	        }
	    }
	    
	    if(isset($_POST['ids'])){
	        $ids = I('post.ids/a');
	        $data_arr=array();
	        foreach($ids as $id){
    	        $data_arr[]=array(
    	            'user_id'=>$id,
    	            'exam_id'=>$exam_id,
    	            'paper_id'=>$exam_data['paper_id'],
    	            'status'=>0
    	        );
	        }
	        if ($this->exams_users_model->addAll($data_arr)) {
	            $this->success("批量报名成功！");
	        } else {
	            $this->error("批量报名成功！");
	        }
	    }
	}

	/**
	 * 删除报名信息
	 */
	public function signin_delete(){

	    $exam_id=I('exam_id');
	    empty($exam_id)&&$this->error("请选择要报名的考试！");
	    
	    if(isset($_GET['id'])){
	        $id = I("get.id",0,'intval');
	        if ($this->exams_users_model->where(array('exam_id'=>$exam_id,'id'=>$id))->delete()) {
	            $this->success("删除成功！");
	        } else {
	            $this->error("删除失败！");
	        }
	    }
	
	    if(isset($_POST['ids'])){
	        $ids = I('post.ids/a');
	
	        if ($this->exams_users_model->where(array('exam_id'=>$exam_id,'id'=>array('in',$ids)))->delete()) {
	            $this->success("删除成功！");
	        } else {
	            $this->error("删除失败！");
	        }
	    }
	}
	/**
	 * 获取指定工种和考试类型的考试
	 * @param unknown $ques_term
	 * @param string $exam_term
	 */
	public function get_exams_json($ques_term=0,$exam_term=0){
	    $ques_term==0||$where['ques_term'] = $ques_term;
	    $exam_term==0||$where['exam_term'] = $exam_term;
	    $where['exam_status']  = 0;
	    
	    $exam_list=$this->exams_model->where($where)->select();
	    //echo $this->exam_model->
	    $data['status']  = 1;
	    $data['content'] = $exam_list;
	    $this->ajaxReturn($data);
	}
	public function get_papers_json($ques_term){
	    $where['paper_term'] = $ques_term;
	    $where['paper_type'] = 1;//正式考题
	     
	    $paper_list=M('paper')->where($where)->select();
	    $data['status']  = 1;
	    $data['content'] = $paper_list;
	    $this->ajaxReturn($data);
	}
	
	// 考试排序
	public function listorders() {
		$status = parent::_listorders($this->exams_model);
		if ($status) {
			$this->success("排序更新成功！");
		} else {
			$this->error("排序更新失败！");
		}
	}
	
  // 考试排序
    public function sorts() {
        $status = parent::_sorts($this->term_relationships_model);
        if ($status) {
            $this->success("排序更新成功！");
        } else {
            $this->error("排序更新失败！");
        }
    }
    
    /**
     * 考试列表处理方法,根据不同条件显示不同的列表
     * @param array $where 查询条件
     */
    private function _lists($where=array()){
        $ques_term_id=I('request.ques_term_id',0,'intval');
        $exam_term_id=I('request.exam_term_id',0,'intval');
        //$type_id=I('request.type_id',0,'intval');
        if(!empty($ques_term_id)){
            $where['ques_term']=$ques_term_id;
            $term=$this->exams_model->where(array('ques_term'=>$ques_term_id))->find();
            $this->assign("ques_term",$term);
        }
        if(!empty($exam_term_id)){
            $where['exam_term']=$exam_term_id;
            $term=$this->exams_model->where(array('exam_term'=>$exam_term_id))->find();
            $this->assign("exam_term",$term);
        }
        /* if(!empty($type_id)){
            $where['exam_type']=$term_id;
            $this->assign("type_id",$type_id);
        } */
    
        $start_time=I('request.start_time');
        if(!empty($start_time)){
            $where['exam_date']=array(
                array('EGT',$start_time)
            );
        }
    
        $end_time=I('request.end_time');
        if(!empty($end_time)){
            if(empty($where['exam_date'])){
                $where['exam_date']=array();
            }
            array_push($where['exam_date'], array('ELT',$end_time));
        }
    
        $keyword=I('request.keyword');
        if(!empty($keyword)){
            $where['exam_name']=array('like',"%$keyword%");
        }
        	
        $this->exams_model
        ->alias("a")
        ->where($where);
    
        if(!empty($ques_term_id)){
            $this->exams_model->join("__QUES_TERMS__ d ON a.ques_term = d.term_id");
        }
        if(!empty($exam_term_id)){
            $this->exams_model->join("__EXAM_TERMS__ b ON a.exam_term = b.term_id");
        }
        $count=$this->exams_model->count();
        	
        $page = $this->page($count, 20);
        	
        $this->exams_model
        ->alias("a")
        ->join("__USERS__ c ON a.user_id = c.id")
        ->where($where)
        ->limit($page->firstRow , $page->listRows)
        ->order("a.exam_start_time DESC");
        //if(!empty($exam_term_id)&&!empty($ques_term_id)){
            $this->exams_model->field('a.*,c.user_login,c.user_nicename,b.name exam_term_name,d.name ques_term_name');
            $this->exams_model->join("__EXAM_TERMS__ b ON a.exam_term = b.term_id");
            $this->exams_model->join("__QUES_TERMS__ d ON a.ques_term = d.term_id");
        /* }else if(!empty($exam_term_id)){
            $this->exams_model->field('a.*,c.user_login,c.user_nicename,b.name exam_term_name');
            $this->exams_model->join("__EXAM_TERMS__ b ON a.exam_term = b.term_id");
        }else if(!empty($ques_term_id)){
            $this->exams_model->field('a.*,c.user_login,c.user_nicename,d.name ques_term_name');
            $this->exams_model->join("__QUES_TERMS__ d ON a.ques_term = d.term_id");
        }
        else{
            
        } */
        $exams=$this->exams_model->select();
        //echo $this->exams_model->getLastSql();
        //增加显示报名和考试信息
        foreach ($exams as &$exam){
            $exam['sign_count']=$this->exams_users_model->where("exam_id=%d",$exam['id'])->count();
        }        
        
        $this->assign("page", $page->show('Admin'));
        $this->assign("formget",array_merge($_GET,$_POST));
        $this->assign("exams",$exams);
    }
    // 获取考试分类树结构 select 形式
    private function _getExamTree(){
        $term_id=empty($_REQUEST['exam_term_id'])?0:intval($_REQUEST['exam_term_id']);
        $result = $this->exam_terms_model->order(array("listorder"=>"asc"))->select();
    
        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($result as $r) {
            $r['str_manage'] = '<a href="' . U("ExamTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("ExamTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a term="js-ajax-delete" href="' . U("ExamTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
            $r['visit'] = "<a href='#'>访问</a>";
            $r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
            $r['id']=$r['term_id'];
            $r['parentid']=$r['parent'];
            $r['selected']=$term_id==$r['term_id']?"selected":"";
            $array[] = $r;
        }
    
        $tree->init($array);
        $str="<option value='\$id' \$selected>\$spacer\$name</option>";
        $taxonomys = $tree->get_tree(0, $str);
        $this->assign("exam_taxonomys", $taxonomys);
    }
    // 获取考试分类树结构 select 形式
    private function _getQuesTree(){
        $term_id=empty($_REQUEST['ques_term_id'])?0:intval($_REQUEST['ques_term_id']);
        $result = $this->ques_terms_model->order(array("listorder"=>"asc"))->select();
    
        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($result as $r) {
            $r['str_manage'] = '<a href="' . U("QuesTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("QuesTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a term="js-ajax-delete" href="' . U("QuesTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
            $r['visit'] = "<a href='#'>访问</a>";
            $r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
            $r['id']=$r['term_id'];
            $r['parentid']=$r['parent'];
            $r['selected']=$term_id==$r['term_id']?"selected":"";
            $array[] = $r;
        }
    
        $tree->init($array);
        $str="<option value='\$id' \$selected>\$spacer\$name</option>";
        $taxonomys = $tree->get_tree(0, $str);
        $this->assign("ques_taxonomys", $taxonomys);
    }
    // 获取考试分类树结构
    private function _getExamTermTree($term=array()){
        $result = $this->exam_terms_model->order(array("listorder"=>"asc"))->select();
    
        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($result as $r) {
            $r['str_manage'] = '<a href="' . U("ExamTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("ExamTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a term="js-ajax-delete" href="' . U("ExamTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
            $r['visit'] = "<a href='#'>访问</a>";
            $r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
            $r['id']=$r['term_id'];
            $r['parentid']=$r['parent'];
            $r['selected']=in_array($r['term_id'], $term)?"selected":"";
            $r['checked'] =in_array($r['term_id'], $term)?"checked":"";
            $array[] = $r;
        }
        $tree->init($array);
        $str="<option value='\$id' \$selected>\$spacer\$name</option>";
        $taxonomys = $tree->get_tree(0, $str);
        $this->assign("exam_taxonomys", $taxonomys);
    }
    // 获取考试分类树结构
    private function _getQuesTermTree($term=array()){
        $result = $this->ques_terms_model->order(array("listorder"=>"asc"))->select();
    
        $tree = new \Tree();
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        foreach ($result as $r) {
            $r['str_manage'] = '<a href="' . U("QuesTerm/add", array("parent" => $r['term_id'])) . '">添加子类</a> | <a href="' . U("QuesTerm/edit", array("id" => $r['term_id'])) . '">修改</a> | <a term="js-ajax-delete" href="' . U("QuesTerm/delete", array("id" => $r['term_id'])) . '">删除</a> ';
            $r['visit'] = "<a href='#'>访问</a>";
            $r['taxonomys'] = $this->taxonomys[$r['taxonomy']];
            $r['id']=$r['term_id'];
            $r['parentid']=$r['parent'];
            $r['selected']=in_array($r['term_id'], $term)?"selected":"";
            $r['checked'] =in_array($r['term_id'], $term)?"checked":"";
            $array[] = $r;
        }
    
        $tree->init($array);
        $str="<option value='\$id' \$selected>\$spacer\$name</option>";
        $taxonomys = $tree->get_tree(0, $str);
        $this->assign("ques_taxonomys", $taxonomys);
    }
    
    // 考试删除
    public function delete(){
        if(isset($_GET['id'])){
            $id = I("get.id",0,'intval');
            if ($this->exams_model->where(array('id'=>$id))->save(array('exam_status'=>3)) !==false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }
    
        if(isset($_POST['ids'])){
            $ids = I('post.ids/a');
            	
            if ($this->exams_model->where(array('id'=>array('in',$ids)))->save(array('exam_status'=>3))!==false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }
    }
    
    // 考试审核
    public function check(){
        if(isset($_POST['ids']) && $_GET["check"]){
            $ids = I('post.ids/a');
            	
            if ( $this->exams_model->where(array('id'=>array('in',$ids)))->save(array('exam_status'=>1)) !== false ) {
                $this->success("审核成功！");
            } else {
                $this->error("审核失败！");
            }
        }
        if(isset($_POST['ids']) && $_GET["uncheck"]){
            $ids = I('post.ids/a');
    
            if ( $this->exams_model->where(array('id'=>array('in',$ids)))->save(array('exam_status'=>0)) !== false) {
                $this->success("取消审核成功！");
            } else {
                $this->error("取消审核失败！");
            }
        }
    }
    
    // 考试置顶
    public function top(){
        if(isset($_POST['ids']) && $_GET["top"]){
            $ids = I('post.ids/a');
            	
            if ( $this->exams_model->where(array('id'=>array('in',$ids)))->save(array('istop'=>1))!==false) {
                $this->success("置顶成功！");
            } else {
                $this->error("置顶失败！");
            }
        }
        if(isset($_POST['ids']) && $_GET["untop"]){
            $ids = I('post.ids/a');
    
            if ( $this->exams_model->where(array('id'=>array('in',$ids)))->save(array('istop'=>0))!==false) {
                $this->success("取消置顶成功！");
            } else {
                $this->error("取消置顶失败！");
            }
        }
    }
    
    // 考试推荐
    public function recommend(){
        if(isset($_POST['ids']) && $_GET["recommend"]){
            $ids = I('post.ids/a');
            	
            if ( $this->exams_model->where(array('id'=>array('in',$ids)))->save(array('recommended'=>1))!==false) {
                $this->success("推荐成功！");
            } else {
                $this->error("推荐失败！");
            }
        }
        if(isset($_POST['ids']) && $_GET["unrecommend"]){
            $ids = I('post.ids/a');
    
            if ( $this->exams_model->where(array('id'=>array('in',$ids)))->save(array('recommended'=>0))!==false) {
                $this->success("取消推荐成功！");
            } else {
                $this->error("取消推荐失败！");
            }
        }
    }
    
    // 考试批量移动
    public function move(){
        if(IS_POST){
            if(isset($_GET['ids']) && $_GET['old_term_id'] && isset($_POST['term_id'])){
                $old_term_id=I('get.old_term_id',0,'intval');
                $term_id=I('post.term_id',0,'intval');
                if($old_term_id!=$term_id){
                    $ids=explode(',', I('get.ids/s'));
                    $ids=array_map('intval', $ids);
    
                    foreach ($ids as $id){
                        $this->term_relationships_model->where(array('object_id'=>$id,'term_id'=>$old_term_id))->delete();
                        $find_relation_count=$this->term_relationships_model->where(array('object_id'=>$id,'term_id'=>$term_id))->count();
                        if($find_relation_count==0){
                            $this->term_relationships_model->add(array('object_id'=>$id,'term_id'=>$term_id));
                        }
                    }
                     
                }
                 
                $this->success("移动成功！");
            }
        }else{
            $tree = new \Tree();
            $tree->icon = array('&nbsp;&nbsp;&nbsp;│ ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
            $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
            $terms = $this->exams_model->order(array("path"=>"ASC"))->select();
            $new_terms=array();
            foreach ($terms as $r) {
                $r['id']=$r['term_id'];
                $r['parentid']=$r['parent'];
                $new_terms[] = $r;
            }
            $tree->init($new_terms);
            $tree_tpl="<option value='\$id'>\$spacer\$name</option>";
            $tree=$tree->get_tree(0,$tree_tpl);
    
            $this->assign("terms_tree",$tree);
            $this->display();
        }
    }
    
   
    
    // 考试回收站列表
    public function recyclebin(){
        $this->_lists(array('exam_status'=>array('eq',3)));
        $this->_getTree();
        $this->display();
    }
    
    // 清除已经删除的考试
    public function clean(){
        if(isset($_POST['ids'])){
            $ids = I('post.ids/a');
            $ids = array_map('intval', $ids);
            $status=$this->exams_model->where(array("id"=>array('in',$ids),'exam_status'=>3))->delete();
            $this->term_relationships_model->where(array('object_id'=>array('in',$ids)))->delete();
            	
            if ($status!==false) {
                $this->success("删除成功！");
            } else {
                $this->error("删除失败！");
            }
        }else{
            if(isset($_GET['id'])){
                $id = I("get.id",0,'intval');
                $status=$this->exams_model->where(array("id"=>$id,'exam_status'=>3))->delete();
                $this->term_relationships_model->where(array('object_id'=>$id))->delete();
    
                if ($status!==false) {
                    $this->success("删除成功！");
                } else {
                    $this->error("删除失败！");
                }
            }
        }
    }
    
    // 考试还原
    public function restore(){
        if(isset($_GET['id'])){
            $id = I("get.id",0,'intval');
            if ($this->exams_model->where(array("id"=>$id,'exam_status'=>3))->save(array("exam_status"=>"0"))) {
                $this->success("还原成功！");
            } else {
                $this->error("还原失败！");
            }
        }
    }
	
}